package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/golang/glog"

	"golang-training-camp/src/week2/models"
	"golang-training-camp/src/week2/service"
)

const (
	USER_NAME = "root"
	PASS_WORD = "root"
	HOST      = "localhost"
	PORT      = "3306"
	DATABASE  = "go_homework"
	CHARSET   = "utf8"
)

var mysqlDb *sql.DB
var userService service.UserService

func main() {

	var err error
	mysqlDb, err = initDB()
	if err != nil {
		panic(err.Error())
	}

	userService, err = initServer(mysqlDb)
	if err != nil {
		panic(err.Error())
	}

	resp, err := userService.FindUser(context.Background(), &models.FindUserReq{})
	if err != nil {
		glog.Errorf("userService.FindUser find error:<%v>", err.Error())
		return
	}
	glog.Infof("userService.FindUser find user:<%+v>", resp)
}

// 初始化链接
func initDB() (*sql.DB, error) {

	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", USER_NAME, PASS_WORD, HOST, PORT, DATABASE, CHARSET)
	var err error
	// 打开连接失败
	mysqlDb, err = sql.Open("mysql", dbDSN)
	//defer MysqlDb.Close();
	if err != nil {
		return nil, errors.New(fmt.Sprintf("数据源配置不正确: %v", err.Error()))
	}

	// 最大连接数
	mysqlDb.SetMaxOpenConns(100)
	// 闲置连接数
	mysqlDb.SetMaxIdleConns(20)
	// 最大连接周期
	mysqlDb.SetConnMaxLifetime(100 * time.Second)

	if err = mysqlDb.Ping(); err != nil {
		return nil, errors.New(fmt.Sprintf("数据库链接失败: %v", err.Error()))
	}

	return mysqlDb, nil
}

// 初始化service单例
func initServer(mysqlDb *sql.DB) (service.UserService, error) {
	return service.NewUserService(mysqlDb)
}
